﻿package Framework.Protocol.CDFProtocol
{
    import Framework.Protocol.*;
    import Framework.Serialize.*;
    import Framework.Util.*;
    import flash.utils.*;

    public class GroupProtocol extends Object implements IProtocol, IBusinessHandler
    {
        private var _buttonProtocol:IProtocol;

        public function GroupProtocol(iprotocol:IProtocol)
        {
            this._buttonProtocol = iprotocol;
        }

        public function handleData(byte:ByteArray, businesshandler:IBusinessHandler, iohandler:IIOHandler, ibusinesshandler:IBusinessHandler) : int
        {
            return this._buttonProtocol.handleData(byte, this, iohandler, businesshandler);
        }

        public function handlePacket(bytes:ByteArray, businesshandler:IBusinessHandler) : Boolean
        {
            var type:uint = 0;
            var len:uint = 0;
            var data:ByteArray = null;
            while (bytes.position < bytes.length)
            {
                
                type = bytes.readUnsignedByte();
                if (type == 255)
                {
                    len = bytes.readUnsignedInt();
                }
                else
                {
                    len = type;
                }
                data = new ByteArray();
                bytes.readBytes(data, 0, len);
                businesshandler.handlePacket(data, null);
            }
            return true;
        }

        public function sendDataEncrypt(bytes:ByteArray, iohandler:IIOHandler) : Boolean
        {
            var stream:SerializeStream = new SerializeStream();
			stream.writeSize(bytes.length);
			stream.byteArray.writeBytes(bytes, 0, bytes.length);
			stream.byteArray.position = 0;
            return this._buttonProtocol.sendDataEncrypt(stream.byteArray, iohandler);
        }

        public function clear() : void
        {
            if (this._buttonProtocol)
            {
                this._buttonProtocol.clear();
            }
        }

        public function get buttonProtocol() : IProtocol
        {
            return this._buttonProtocol;
        }

        public function set buttonProtocol(buttonProtocol:IProtocol) : void
        {
            this._buttonProtocol = buttonProtocol;
        }
    }
}
